#!usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import time
import threading
from Tkinter import *
import tkMessageBox
def reset_successful():
    tkMessageBox.showinfo("SCARA机器人复位", "复位成功！                   ")
def save_successful():
   tkMessageBox.showinfo("SCARA机器人程序", "保存成功！                   ")
def send_data(port, arduino_ip_port, data, delay):#本地端口号，arduino地址和端口，数据,延时
    host=''  
    big_port=port  
    big=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)  
    big.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)  
    big.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1)  
    big.bind((host,big_port))
    big_receive_flag = 0
    big_finish_flag = 0      
    big_ip_port = arduino_ip_port
    sending_data = data
    big.sendto(sending_data, big_ip_port)
    while big_receive_flag == 0:
        h = 0
        big_data,big_addr=big.recvfrom(1024)
        if big_addr == big_ip_port and big_data == 'received_data':
            print 'The machine',big_addr,'received -->',big_data
            big_receive_flag = 1
            h = 1
            time.sleep(delay)
        if h == 0:
            big.sendto(sending_data, big_ip_port)
    while big_finish_flag == 0:
        big_data,big_addr=big.recvfrom(1024)
        if big_addr == big_ip_port and big_data == 'finished_action':
            print 'the machine',big_addr,'was finished action'
            big_finish_flag = 1
class send_data_thread(threading.Thread ):
    def __init__(self, port, arduino_ip_port, data, delay):#本地端口号，arduino地址和端口，数据,延时
        threading.Thread.__init__(self)
        self.port = port
        self.arduino_ip_port = arduino_ip_port
        self.data = data
        self.delay = delay
    def run(self):
        print 'start -->',self.data
        send_data(self.port, self.arduino_ip_port, self.data, self.delay)
        print 'ended -->',self.data
def moveto(big, lit):     #('1,1202', '1,680')<'指令大臂最终位置'，'指令,小臂最终位置'>
    threads = []
    thread1 = send_data_thread(10000, ('169.254.225.100', 8888), big, 0)
    thread2 = send_data_thread(10001, ('169.254.225.101', 8889), lit, 0.01)
    threads.append(thread1)
    threads.append(thread2)
    for t in threads:
        t.setDaemon(True)   #设置为守护进程
        t.start()           #进程开始
    thread1.join()          #等待线程结束
    thread2.join()          #等待线程结束
def reset_lo():
    send_data(10001, ('169.254.225.101', 8889), '2,0000', 0)
    send_data(10000, ('169.254.225.100', 8888), '2,0000', 0)
    reset_successful()
def interface():
    str_big_position = 0
    str_lit_position = 0
    light = 0
    cycle = 1
    def form(p):
        result = ''
        if 0<=p<10:
            result = '000'+str(p)
        if 10<=p<100:
            result = '00'+str(p)
        if 100<=p<1000:
            result = '0'+str(p)
        if 1000<=p<10000:
            result = str(p)
        return result
    def go_here_command():
        global str_big_position
        global str_lit_position
        big_position = big.get()#int
        lit_position = lit.get()#int
        str_big_position = form(big_position)
        str_lit_position = form(lit_position)
        moveto('1,0'+str_big_position, '1,'+str_lit_position)
        print '***********OK***********'
    def open_light():
        global light
        light=1
        send_data(10000, ('169.254.225.100', 8888), '3,0001', 0)#arduino 3 端口
    def close_light():
        global light
        light=0
        send_data(10000, ('169.254.225.100', 8888), '4,0000', 0)#arduino 3 端口
    def get_program():
        w = program.get(1.0, END)
        return w
    def save_program():
        with open('programe.pro','w') as f:
            f.write(get_program())
            f.close()
        save_successful()			
    def insert_program():
        global light
        global str_big_position
        global str_lit_position
        l = light
        b = str_big_position
        t = str_lit_position
        program.insert(INSERT, '1,'+str(b)+',2,'+str(t)+',3,1,4,'+str(l)+',5,0;\n')
    def sak_run_program():
        yes_no = tkMessageBox.askyesno('请仔细检查确保运行环境安全','确定要运行吗？                      ')
        if yes_no == 1:
		    run_program()
    def sak_run_program_cycle():
        yes_no = tkMessageBox.askyesno('请仔细检查确保运行环境安全','    为了软件在linux和windows上的兼容性，机器人在运行时只能通过硬件停止，确定要循环运行吗？')
        if yes_no == 1:
		    run_program_recycle()
    def run_program_recycle():
        global cycle
        cycle = 3
        while (cycle >= 1):
            cycle -= 1
            run_program()
    def run_program():
        big_p = ''
        lit_p = ''
        lig_p = ''
        with open('programe.pro','r') as f:
            program = f.read()
            str_program = str(program)
            list_program = str_program.split(';')
            for pro in list_program[:-1]:
                date = pro.split(',')
                if big_p != date[1] or lit_p != date[3]:
                    big_p = date[1]
                    lit_p = date[3]
                    moveto('1,0'+big_p, '1,'+lit_p)
                delay_time_m = int(date[5])
                if delay_time_m != 0:
                    print('delay'+str(delay_time_m)+'s')
                    time.sleep(delay_time_m)
                if lig_p != date[7]:
                    lig_p = date[7]
                    if lig_p == '1':
                        time.sleep(0.5)
                        open_light()
                        time.sleep(0.3)
                    if lig_p == '0':
                        time.sleep(0.5)
                        close_light()
                        time.sleep(0.5)
                delay_time = int(date[9])
                if delay_time != 0:
                    print('delay'+str(delay_time)+'s')
                    time.sleep(delay_time)
    root = Tk()
    root.title('SCARA机器人控制程序-王振豪')
    root.iconbitmap('3.ico')
    top = LabelFrame(root, text="", padx=5, pady=5)
    top.grid(row=0, column=0, sticky=W)
    group_scale = LabelFrame(top, text="手动调试位置", padx=5, pady=5)
    group_scale.grid(row=0, column=0, sticky=W)
    Label(group_scale,text='大臂角度：').grid(row=0, column=0, sticky=W)
    Label(group_scale,text='小臂角度：').grid(row=1, column=0, sticky=W)	
    big = Scale(group_scale, from_=0, to=1200, length=300, orient=HORIZONTAL)
    big.grid(row=0, column=1, sticky=W)
    lit = Scale(group_scale, from_=0, to=2288, length=300, orient=HORIZONTAL)
    lit.grid(row=1, column=1, sticky=W)
	
    reset = Button(group_scale,text='复位',command=reset_lo)
    reset.grid(row=0, column=2, sticky=W, padx=5, pady=6)
    go_here = Button(group_scale,text='调试',command=go_here_command)
    go_here.grid(row=1, column=2, sticky=W, padx=5, pady=6)
    put_up = Button(group_scale,text='抓起',command=open_light)
    put_up.grid(row=0, column=3, sticky=W, padx=5, pady=6)
    put_down = Button(group_scale,text='放下',command=close_light)
    put_down.grid(row=1, column=3, sticky=W, padx=5, pady=6)
	
    auto = LabelFrame(top, text="自动运行", padx=5, pady=5)
    auto.grid(row=0, column=1, sticky=W)
    auto_run = Button(auto, text='单次运行',command=sak_run_program, width=20, height=2)
    auto_run.grid(row=0, column=0)
    auto_run_c = Button(auto, text='循环运行',command=sak_run_program_cycle, width=20, height=2)
    auto_run_c.grid(row=1, column=0)

    group_text = LabelFrame(root, text="机器人运行程序（可手动编辑）", padx=5, pady=5)
    group_text.grid(row=1, column=0, sticky=W)
    program = Text(group_text,width=91,height=20)#106，20
    program.pack()
    save_program = Button(group_text,text='保存',command=save_program)
    save_program.pack(side=RIGHT, padx=5, pady=5)
    insert_program = Button(group_text,text='插入',command=insert_program)
    insert_program.pack(side=RIGHT, padx=5, pady=5)
    mainloop()
interface()